package com.weixing.mall.provider.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weixing.mall.base.enums.IdGenTagEnum;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.core.utils.CommonUtil;
import com.weixing.mall.leaf.api.service.IdGenServiceRpc;
import com.weixing.mall.provider.api.model.dto.MemberAgentBindDto;
import com.weixing.mall.provider.api.model.dto.UserDto;
import com.weixing.mall.provider.api.model.enums.AgentLevelEnum;
import com.weixing.mall.provider.api.model.enums.AgentTypeEnum;
import com.weixing.mall.provider.api.model.vo.SysUserVo;
import com.weixing.mall.provider.api.service.MemberServiceRpc;
import com.weixing.mall.provider.api.service.SysUserRpcService;
import com.weixing.mall.provider.mapper.UserOldMapper;
import com.weixing.mall.provider.model.domain.*;
import com.weixing.mall.provider.service.*;
import com.weixing.mall.provider.util.AgentUtil;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Small
 * @since 2020-06-14
 */
@Service
public class UserOldServiceImpl extends ServiceImpl<UserOldMapper, UserOld> implements IUserOldService {

    @Autowired
    private IAgentService agentService;
    @Autowired
    private IdGenServiceRpc idGenServiceRpc;
    @Autowired
    private IAgentInfoService agentInfoService;
    @Autowired
    private IAgentAccountService agentAccountService;
    @Autowired
    private MemberServiceRpc memberServiceRpc;
    @Autowired
    private IOfficePromoteService officePromoteService;
    @Autowired
    private SysUserRpcService sysUserRpcService;

    private static final String lv3 = "AGENT_DISCOUNT_LV3";
    private static final String lv2 = "AGENT_DISCOUNT_LV2";
    private static final String lv1 = "AGENT_DISCOUNT_LV1";
    private static final String lv0 = "DEALER_DISCOUNT";
    private static final String GOLD_DEALER = "经销商1";


    private SysUserVo qitaKefu;

//    /**
//     *  等级解释：
//     *  AGENT_DISCOUNT_LV3   三级代理
//     *  AGENT_DISCOUNT_LV2   二级代理
//     *  AGENT_DISCOUNT_LV1   一级代理
//     *  DEALER_DISCOUNT      普通经销商
//     *  DEALER_DISCOUNT_LV1  金级经销商
//     *  DEALER_DISCOUNT_LV2  银级经销商
//     *
//     * 导入规范
//     * *经销商：sys_user 表中 user_lvl字段以 DEALER_DISCOUNT 开头的为经销商
//     * **1、qq字段为 经销商1 的统一设为金级经销商
//     * **2、qq字段为 ！经销商1 的统一设为银级经销商
//     * **3、TODO qq字段为 null 的该咋处理
//     * **4、sys_office_promote表中parent_id为 0 的 统一新建一个客服 名称为 其他 与代理做绑定
//     * **5、login_flag 为0 代理商禁用
//     */
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void syncAgentLv(String lv) {
//        // 查询 其他 客服是否存在
//        this.qitaKefu = selectCompanyKefu();
//        QueryWrapper<UserOld> wrapper = new QueryWrapper<UserOld>();
//        if (lv.equals(lv0)) {
//            wrapper.like("user_lvl", lv);
//        } else {
//            wrapper.eq("user_lvl", lv);
//        }
//        List<UserOld> list = list(wrapper);
//        int size = list.size();
//        for (int i = 0; i< size; i++){
//            System.out.println("共" + size + "条，第" + i + "条");
//            // 创建代理商
//            createAgent(list.get(i));
//        }
//    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Agent createAgent(UserOld userOld,SysUserVo qitaKefu) {
        this.qitaKefu = qitaKefu;
        OfficePromote userOldOfficePromote = officePromoteService.getById(userOld.getId());
        Agent agent = new Agent();
        agent.setIsEnable("0".equals(userOld.getLoginFlag()) ? WhetherEnum.NO.getValue() : WhetherEnum.YES.getValue());
        agent.setMobile(userOld.getMobile());
        agent.setPassword(CommonUtil.encryptPassword(userOld.getMobile().substring(5)));
        long agentSn = idGenServiceRpc.segmentKey(IdGenTagEnum.AGENT_SN.getValue());
        agent.setAgentSn(String.valueOf(agentSn));
        agent.setAgentName(userOld.getNickname());
        agent.setEmail(userOld.getEmail());
        agent.setWechatNum(userOld.getWechat());
        agent.setWechatNickName(userOld.getName());
        agent.setAgentType(AgentTypeEnum.SILVER.getValue());
        AgentLevelEnum agentLv = getAgentLv(userOld);
        agent.setAgentLevel(agentLv.getValue());
        String qq = userOld.getQq();
        agent.setLabel(qq);
        agent.setAgentType(GOLD_DEALER.equals(qq) ? AgentTypeEnum.GOLD.getValue() : AgentTypeEnum.SILVER.getValue());
        agent.setRebateRule(agentLv.getRebateRule().getValue());
        System.out.println(userOld.getId() + "------" + userOld.getMobile() + "---------" + userOldOfficePromote.getDiscount() + "------------" + userOld.getNickname());
        Double dis = null == userOldOfficePromote.getDiscount() || 0 == userOldOfficePromote.getDiscount().doubleValue() ? userOldOfficePromote.getDefaultDiscount() : userOldOfficePromote.getDiscount();
        agent.setDiscount(new BigDecimal(dis));
        // 处理父id
        String parentId = userOldOfficePromote.getParentId();
        System.out.println("pid:" + "--------------" + parentId);
        Agent agentParent = null;
        if ("0".equals(parentId)) {
            synchronized (UserOldServiceImpl.class) {
                if (null == this.qitaKefu) {
                    // 新建一个其他客服
                    this.qitaKefu = createQitaKefu();
                }
            }
            agent.setParentId(0L);
            agent.setCustomerId(qitaKefu.getId());
            agent.setCustomerName(qitaKefu.getRealName());
            agent.setCustomerBindTime(new Date());
        } else {
            // 父级
            UserOld parent = getById(parentId);
            if (StringUtil.isEmpty(parent.getUserLvl())) {
                // 父级为客服
                agent.setParentId(0L);
                SysUserVo data = createKefu(parent);
                agent.setCustomerId(data.getId());
                agent.setCustomerName(data.getRealName());
                agent.setCustomerBindTime(new Date());
            } else {
                // 父级为代理
                String parentIds = userOldOfficePromote.getParentIds();
                System.out.println("pids:" + parentIds);
                String[] split = parentIds.split(",");
                // 直接上级id
                String ppid = split[split.length - 1];
                System.out.println("ppid:" + ppid);
                UserOld userOldParent = getById(ppid);
                agentParent = agentService.findByMobile(userOldParent.getMobile());
                agent.setParentId(agentParent.getId());
                agent.setCustomerId(agentParent.getCustomerId());
                agent.setCustomerName(agentParent.getCustomerName());
                agent.setCustomerBindTime(new Date());
            }
        }
        agent.setIsBind(WhetherEnum.YES.getValue());
        agentService.save(agent);
        // 更新代理结构树
        if (null == agentParent) {
            agent.setAgentTreePath(AgentUtil.calcAgentTreePath(agent));
        } else {
            agent.setAgentTreePath(AgentUtil.calcAgentTreePath(agentParent.getAgentTreePath(), agent));
        }
        AgentUtil.updateAgentTree(agent);
        agentService.updateById(agent);
        // 创建代理商账户表
        AgentAccount agentAccount = new AgentAccount();
        agentAccount.setAgentId(agent.getId());
        agentAccountService.save(agentAccount);
        // 创建代理商info表
        AgentInfo info = new AgentInfo();
        info.setAgentId(agent.getId());
        info.setIdCard(userOld.getIdentityNumber());
        agentInfoService.save(info);
        MemberAgentBindDto bindDto = new MemberAgentBindDto();
        bindDto.setAgentId(agent.getId());
        bindDto.setAgentSn(agent.getAgentSn());
        bindDto.setAgentName(agent.getAgentName());
        bindDto.setPassword(userOld.getMobile().substring(5));
        bindDto.setMobile(agent.getMobile());
        Result result = memberServiceRpc.saveOrUpdateMember(bindDto);
        if (!result.isSuccess()) {
            throw new BusinessException("处理代理商和会员绑定关系时异常，请联系管理员处理");
        }

        userOld.setImFlag(1);
        updateById(userOld);
        return agent;
    }


    private AgentLevelEnum getAgentLv(UserOld old) {
        String userLvl = old.getUserLvl();
        AgentLevelEnum lv = AgentLevelEnum.DEALER;
        switch (userLvl) {
            case lv0:
                lv = AgentLevelEnum.DEALER;
                break;
            case lv1:
                lv = AgentLevelEnum.LEVEL_1;
                break;
            case lv2:
                lv = AgentLevelEnum.LEVEL_2;
                break;
            case lv3:
                lv = AgentLevelEnum.LEVEL_3;
                break;
            default:
                break;

        }
        return lv;
    }


    /**
     * 方法描述: 查询其他客服
     *
     * @Author Small
     * @param
     * @Date 2020/6/15 16:20
     * @return com.weixing.mall.provider.api.model.vo.SysUserAuthVo
     */
    private SysUserVo selectCompanyKefu() {
        Result<SysUserVo> companykefu = sysUserRpcService.selectByLoginName("companykefu");
        if (!companykefu.isSuccess()) {
            throw new BusinessException("查询其他客服时异常");
        }
        return companykefu.getData();
    }


    /**
     * 方法描述: 新建其他用户
     * @Author Small
     * @param
     * @Date 2020/6/15 16:22
     * @return com.weixing.mall.provider.api.model.vo.SysUserAuthVo
     */
    private SysUserVo createQitaKefu() {
        UserDto userDto = new UserDto();
        userDto.setDeptId(4L);
        userDto.setEmail("");
        userDto.setLoginName("companykefu");
        userDto.setRealName("其他");
        userDto.setNickName("公司客服");
        userDto.setMobile("18736000000");
        userDto.setWechatNum("wx00190");
        userDto.setLoginPwd("1234qwer");
        Long[] roles = new Long[]{10L, 23L};
        userDto.setRoles(roles);
        Result<SysUserVo> result = sysUserRpcService.createUser(userDto);
        if (!result.isSuccess()) {
            throw new BusinessException("新增后台用户失败");
        }
        SysUserVo data = result.getData();
        return data;
    }

    /**
     * 方法描述: 创建客服
     * @Author Small
     * @param parent
     * @Date 2020/6/15 16:29
     * @return com.weixing.mall.provider.api.model.vo.SysUserVo
     */
    private SysUserVo createKefu(UserOld parent) {
        Result<SysUserVo> voResult = sysUserRpcService.selectByLoginName(parent.getMobile());
        if (!voResult.isSuccess()) {
            throw new BusinessException("创建客服前查询客服异常");
        }
        SysUserVo data = voResult.getData();
        if (null != data) {
            return data;
        }
        UserDto userDto = new UserDto();
        userDto.setDeptId(4L);
        userDto.setEmail(parent.getEmail());
        userDto.setLoginName(parent.getMobile());
        userDto.setRealName(parent.getName());
        userDto.setNickName(parent.getNickname());
        userDto.setMobile(parent.getMobile());
        userDto.setWechatNum(parent.getWechat());
        userDto.setLoginPwd(parent.getMobile().substring(5));
        Long[] roles = new Long[]{10L, 23L};
        userDto.setRoles(roles);
        Result<SysUserVo> result = sysUserRpcService.createUser(userDto);
        if (!result.isSuccess()) {
            throw new BusinessException("新增后台用户失败");
        }
        return result.getData();
    }
}
